//
//  GroupViewController.m
//  FDSMeshLibDemo
//
//  Created by LEIPENG on 2022/6/9.
//

#import "GroupViewController.h"
#import "GroupEditViewController.h"
#import "TestViewController.h"
#import "NodeListTableViewCell.h"
#import "ListCreatTableViewCell.h"

@interface GroupViewController ()<UITableViewDataSource, UITableViewDelegate, GetNodeEventResponseDelegate, GetListCreatResponseDelegate, JMDropMenuDelegate>

@property (nonatomic, assign) NSInteger selectRow;
@property (nonatomic, strong) MeshTool *meshTool;
@property (weak, nonatomic) IBOutlet UIButton *addButton;
@property (weak, nonatomic) IBOutlet UITableView *tableview;

@end

@implementation GroupViewController

#pragma mark - Initialize
- (void)InitializeCode{
    self.meshTool = [MeshTool shareInstance];
    self.title = @"组别";
    self.selectRow = 0;
    self.addButton.layer.cornerRadius = 15;
    self.addButton.layer.masksToBounds = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationRefreshNodes) name:FDS_REFRESH_NODES_STATE object:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self InitializeCode];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.meshTool refreshNodesAndGroups];
    [self.tableview reloadData];
}
#pragma mark - NSNotificationCenter
- (void)notificationRefreshNodes{
    NSLog(@"--- 刷新组别数据 ---");
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(configNodePublish) object:nil];
    [self performSelector:@selector(configNodePublish) withObject:nil afterDelay:2.0];
}
- (void)configNodePublish {
    WeakSelf
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf.meshTool refreshNodesAndGroups];
        [weakSelf.tableview reloadData];
    });
}
#pragma mark - UIButton
- (IBAction)clickCreateBtn:(UIButton *)sender {
    [self getListCreatResponse];
}
#pragma mark - GetListCreatResponseDelegate
- (void)getListCreatResponse{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"新增组别？" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = [NSString stringWithFormat:@"Group-%lu",(self.meshTool.groupList.count+1)];
    }];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {}]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        UITextField *textfield = alertController.textFields.firstObject;
        if (textfield.text.length) {
            UInt16 groupAddress = 0x0000;
            if ([FDSMeshApi createGroup:textfield.text address:&groupAddress]) {
                NSLog(@"groupAddress ---> %04X", groupAddress);
                [self.meshTool refreshNodesAndGroups];
                self.meshTool.studioModel.meshJson = [FDSMeshApi getCurrentMeshJson];
                [self.meshTool codingMeshData:self.meshTool.meshModel];
                [self.tableview reloadData];
            }
        } else {
            [SVProgressHUD showErrorWithStatus:@"无效的组别名称！"];
        }
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark - GetNodeEventResponseDelegate
- (void)getNodeEventResponseEdit:(NSInteger)rowIndex{
    self.selectRow = rowIndex;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:rowIndex inSection:0];
    CGRect rectInTableView = [self.tableview rectForRowAtIndexPath:indexPath];
    CGRect rectInSuperview = [self.tableview convertRect:rectInTableView toView:[self.tableview superview]];
    [JMDropMenu showDropMenuFrame:CGRectMake(SCREEN_WIDTH - 140 - 20, rectInSuperview.origin.y+rectInSuperview.size.height+StatusBarAndNavigationBarHeight-100-20, 140, 150) ArrowOffset:60 TitleArr:@[
        @"删除",
        @"重命名",
        @"编辑"] ImageArr:@[@"",@""] Type:JMDropMenuTypeQQ LayoutType:JMDropMenuLayoutTypeTitle RowHeight:50 Delegate:self];
}
- (void)getNodeEventResponseSwitch:(NSInteger)rowIndex sw:(BOOL)isSw{
    FDSMeshGroupModel *groupModel = self.meshTool.groupList[rowIndex];
    [FDSCommandApi changeLightSwitch:groupModel.address isSwitch:isSw];
}
#pragma mark - JMDropMenuDelegate
- (void)didSelectRowAtIndex:(NSInteger)index Title:(NSString *)title Image:(NSString *)image{
    if (self.selectRow < self.meshTool.groupList.count) {} else {
        return;
    }
    FDSMeshGroupModel *groupModel = self.meshTool.groupList[self.selectRow];
    if (index == 0) {
        // 删除
        [FDSMeshApi removeGroup:groupModel];
        [self.meshTool refreshNodesAndGroups];
        self.meshTool.studioModel.meshJson = [FDSMeshApi getCurrentMeshJson];
        [self.meshTool codingMeshData:self.meshTool.meshModel];
        [self.tableview reloadData];
    } else if (index == 1) {
        // 重命名
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"重命名组别？" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
        [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.text = groupModel.name;
        }];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {}]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            UITextField *textfield = alertController.textFields.firstObject;
            if (textfield.text.length) {
                [FDSMeshApi renameGroup:groupModel name:textfield.text];  
                [self.meshTool refreshNodesAndGroups];
                self.meshTool.studioModel.meshJson = [FDSMeshApi getCurrentMeshJson];
                [self.meshTool codingMeshData:self.meshTool.meshModel];
                [self.tableview reloadData];
            } else {
                [SVProgressHUD showErrorWithStatus:@"无效的组别名称！"];
            }
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    } else if (index == 2) {
        // 编辑
        GroupEditViewController *viewController = [[GroupEditViewController alloc] init];
        viewController.hidesBottomBarWhenPushed = YES;
        viewController.address = groupModel.address;
        [self.navigationController pushViewController:viewController animated:YES];
    }
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return self.meshTool.groupList.count;
    } else {
        if (self.meshTool.groupList.count == 0) {
            return 1;
        }
        return 0;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10.0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 100;
    }
    return 300;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        NodeListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([NodeListTableViewCell class])];
        if (!cell){
            cell = [[NSBundle mainBundle] loadNibNamed:@"NodeListTableViewCell" owner:nil options:nil][0];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.rowIndex = indexPath.row;
        cell.delegate = self;
        FDSMeshGroupModel *groupModel = self.meshTool.groupList[indexPath.row];
        cell.titleLabel.text = groupModel.name;
        cell.subTitleLabel.text = [NSString stringWithFormat:@"%ld个节点",groupModel.groupDevices.count];
        cell.iconImageview.image = [UIImage imageNamed:@"setting_05"];
        return cell;
    } else {
        ListCreatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ListCreatTableViewCell class])];
        if (!cell){
            cell = [[NSBundle mainBundle] loadNibNamed:@"ListCreatTableViewCell" owner:nil options:nil][0];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        cell.creatLabel.text = @"当前没有组别，请先创建组别~";
        [cell.creatButton setTitle:@"创建组别" forState:(UIControlStateNormal)];
        return cell;
    }
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        FDSMeshGroupModel *groupModel = self.meshTool.groupList[indexPath.row];
        TestViewController *viewController = [[TestViewController alloc] init];
        viewController.testModel = groupModel;
        viewController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:viewController animated:YES];
    }
}

@end
